import socket,sys,os
import select
from time import time, ctime
from threading import *
#import partie

conn_client={}

mySocketReception=None
mySocketEmission=None
thReception=None
listePartie=list()
listeJoueur=list()

class Serveur:
    
    def __init__(self,HOST,PORT):
        #global conn_client

        #self.TAILLE_BLOC=1024 

        self.mySocketReception=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
        self.mySocketEmission=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

        try:
            self.mySocketReception.bind((HOST,PORT))
            #self.mySocketEmission.connect((HOST,PORT+1))

        except socket.error:
            print "La liaison a echouee"
            sys.exit()
        
        #self.mySocketEmission.send("serveurPret") 
        #JeuServeur=GestionduJeu()
        self.mySocketReception.listen(5)
        while 1:
        # en attente qu'un client se connecte
            newsock, addr = self.mySocketReception.accept()
            print "connection entrante : %s:%d" % addr
         
            thReception=ThreadReception(newsock,self,HOST)
            thReception.start()
          
            it=thReception.getName()
            conn_client[it]=newsock     

        mySocketReception.close()
        mySocketEmission.close()
    

class ThreadReception(Thread):
     def __init__(self,connexion,parent,host,numpartie=0):
         Thread.__init__(self)
         self.connexion=connexion
         #pour connaitre pour chaque thread
         #a quelle partie et quel joueur elle appartient
         self.npartie=numpartie
         self.parent=parent
         self.host=host
         self.tourne=True
          
     #le run est le meme pour toutes les threads
     #les threads de tous les clients sont actives en meme temps
     def run(self):
         nom=self.getName()
         while self.tourne:
              msgClient=self.connexion.recv(1024)
              print msgClient

              if msgClient=="clientPret":
                  try:
                      self.parent.mySocketEmission.connect((self.host,port+1))
                  except socket.error:
                      print "La liaison a echouee"
                      sys.exit()
                  print "socketEmission"
                  self.parent.mySocketEmission.send("serveurPret")

              if msgClient=="listePartiesEnAttente":
                  self.parent.mySocketEmission.send("nbPartiesEnAttente\n")
                  self.parent.mySocketEmission.send("2\n")
                  self.parent.mySocketEmission.send("ListePartiesEnAttente\n")
                  self.parent.mySocketEmission.send("partie,2,1,1,nom;partie,2,1,2,nom")



              # if (msgClient=="partie"):
              #       msg2=self.connexion.recv(1024)
              #       #creation de la partie
              #       listePartie.append(Partie(msg2,self.emission))
                   
              # if (msgClient=="listePartiesEnAttente"):
              #     #ici tout est imbrique
              #     #les messages sont a la suite des autres
              #     #...
              #     #non?
              #     #...
              #     n=0
              #     c=""
              #     for i in self.listePartie:
              #         if i.getetat==-1:
              #             #partie en attente de joueur
              #             n+=1
              #             c=c+";"+i.getinfo()
              #     self.emission.send("nbPartiesEnAttente")
              #     self.emission.send(n)
              #     self.emission.send("listePartiesEnAttente")
              #     self.emission.send(c)

              # if (msgClient=="numPartieChoisie"):
              #     msg2=sock.recv(1024)
              #     self.njoueur=listPartie[int(msg2)].addjoueur(msg3,self.emission)
              #     self.npartie=int(msg2)
                  
              #         msg3=self.newsock.recv(1024)
              # if (msg3=="numPartieChoisie"):
              #     numP=self.newsock.recv(1024)
              #     msg4=self.newsock.recv(1024)
              #     if (msg4=="nomJoueur"):
              #         nomJ=self.newsock.recv(1024)
              #           #ajout du joueur dans la partie
              #        self.listePartie[numP].addjoueur(nomJ,self.newsock)
                  
              # if (msgClient=="matrice"):
              #     msg2=sock.recv(1024)
              #     listePartie[self.numPartie].emiMatrice(self.emission,msg2)

              # if (msgClient=="bombeDecouverte"):
              #     listePartie[self.numPartie].bombe(self.emission)


              # if (msgClient=="click"):
              #     #on test si c'est a se joueur de jouer
              #     if listePartie[self.numPartie].quijoue(self.emission):
              #         msg2=self.connexion.recv(1024)
              #         testmsg=msg2.split(",")
              #         if (len(testmsg)==2 & type(int(testmsg[0]))==int & type(int(testmsg[1]))==int):
              #             listePartie[self.numPartie].click(msg2,self.emission)
              #         else :
              #             self.emission.send("Pb_click")
              #     else :
              #         self.emission.send("Pb_PasToi")
                          

              # if (msgClient=="partieGagnee"):
              #     listePartie[self.numPartie].gagne(self.emission)  

              # if (msgClient=="partiePerdu"):
              #     listePartie[self.numPartie].perdu(self.emission)
              
              # if not msgClient: break
              # self.writeDate(sock)
	
        

if __name__=="__main__":
    import sys
    host = 'localhost'
    port = 4000
    if len(sys.argv)<2:
        print "default listen port : %d"%port
        print "default localhost : %s"%host
    elif len(sys.argv)==2:
        if len(sys.argv[1])>5:
            host = sys.argv[1]
            print "localhost given : %s"%host
        else:       
            port = int(sys.argv[1])
            print "listened port : %d"%port
    else:
        if len(sys.argv[1])>len(sys.argv[2]):
            host = sys.argv[1]
            port = int(sys.argv[2])
        else:
            host = sys.argv[2]
            port = int(sys.argv[1])
    
        print "localhost given: %s"%host
        print "listened port: %d"%port

    Serveur(host,port)
